import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { systemStatusStore } from '@/store/system/status';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import router from '@/router';

// 创建axios实例
const server = axios.create({
  baseURL: import.meta.env.VITE_API_PATH, // 设置API的基础URL
});

// 请求拦截器
server.interceptors.request.use(
  (config: AxiosRequestConfig): any => {
    // 可在请求发送前对config进行修改，如添加请求头等
    const headers = config.headers || {};
    headers['Authorization'] = 'Bxxx';
    config.headers = headers;
    return config;
  },
  (error: AxiosError) => {
    // 处理请求错误
    console.log(error);
    alertError(error.message);
    return Promise.reject(error);
  },
);

// 响应拦截器
server.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, status, msg, data } = response.data;
    switch (code) {
      case 200:
        if (status) {
          return data || msg;
        } else {
          //业务错误
          alertError(msg);
          console.log(code, msg);
          return Promise.reject(new Error(msg));
        }
      case 401:
        //会话失效，跳转至登录
        alertError('session expired, go to the login');
        const currentUrl = window.location.origin + window.location.pathname + '#';
        const toPath = systemStatusStore().routerToPtah ?? router.currentRoute.value.fullPath;
        window.location.href = import.meta.env.VITE_API_CAS.concat(currentUrl + toPath);
        return Promise.reject(new Error(msg));
      default:
        //未知错误
        alertError(msg);
        console.log(code, msg);
        return Promise.reject(new Error(msg));
    }
  },
  (error: AxiosError) => {
    // 处理响应错误
    console.log(error);
    alertError(error.message);
    return Promise.reject(error);
  },
);

const alertError = (msg: string) => {
  ElMessage.error({
    message: msg || 'Error',
    duration: 10000,
    showClose: true,
  });
};

function createRequest(services: AxiosInstance) {
  return function <T>(config: AxiosRequestConfig): Promise<T> {
    return services(config);
  };
}

export default createRequest(server);
